package com.ruoyi.paint.admin.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.paint.admin.domain.*;
import com.ruoyi.paint.admin.domain.Dto.CarColorSchemeDTO;
import com.ruoyi.paint.admin.service.ITqCarsService;
import com.ruoyi.paint.admin.service.TqColorschemesService;
import com.ruoyi.paint.admin.service.TqSchemetintsService;
import com.ruoyi.paint.admin.utils.BeanCopyUtils;
import com.ruoyi.paint.admin.utils.PinyinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * H5页面汽车信息Controller
 *
 * @author itchen
 * @date 2024-07-01
 */
@RestController
@RequestMapping("/front/paint/cars")
public class FrontCarsController extends BaseController {
    @Autowired
    private ITqCarsService tqCarsService;

    @Autowired
    private TqColorschemesService tqColorschemesService;
    @Autowired
    private TqSchemetintsService tqSchemetintsService;

//    private static final Collator BRAND_COLLATOR = Collator.getInstance(Locale.CHINA);
//    private static final Collator MODEL_COLLATOR = Collator.getInstance(Locale.CHINA);
//    private static final Collator COLOR_NAME_COLLATOR = Collator.getInstance(Locale.CHINA);
//
//    public static List<TqCarsInfo> sortCars(List<TqCarsInfo> cars) {
//        return cars.stream()
//                // 使用Collator进行中文排序，先按品牌，然后模型，接着颜色名称，最后生产年份
//                .sorted(Comparator.comparing((TqCarsInfo car) -> BRAND_COLLATOR.getCollationKey(car.getBrand()))
//                        .thenComparing(car -> MODEL_COLLATOR.getCollationKey(car.getModel()))
//                        .thenComparing(car -> COLOR_NAME_COLLATOR.getCollationKey(car.getColorName()))
//                        .thenComparing(TqCarsInfo::getYear))
//                .collect(Collectors.toList());
//    }
    /**
     * 查车列表（移动）
     */
    @GetMapping("/list/move")
    public TableDataInfo listMove(TqCarsInfo tqCarsInfo) {
//        startPage();
        List<TqCarsInfo> list = tqCarsService.selectTqCarsList(tqCarsInfo);
        for (TqCarsInfo carsInfo : list) {
            carsInfo.setId(String.valueOf(carsInfo.getId()));
        }
        return getDataTable(list);
    }
//    @GetMapping("/list/move/sort")
//    public TableDataInfo listMoveSort(TqCarsInfo tqCarsInfo) {
//        List<TqCarsInfo> allList = tqCarsService.selectTqCarsList(tqCarsInfo);
//        // 使用Java 8 Stream API进行筛选
//        List<TqCarsInfo> filteredList = allList.stream()
//                .filter(carsInfo -> carsInfo.getSort() == 1)
//                .collect(Collectors.toList());
//
//        // 修改ID为字符串表示
//        for (TqCarsInfo carsInfo : filteredList) {
//            carsInfo.setId(String.valueOf(carsInfo.getId()));
//        }
//        return getDataTable(filteredList);
//    }

    @PostMapping("/updateSort")
    public AjaxResult updateSort(Long id ,Integer sort) {
        if (sort == 1){
            boolean update = isUpdate(id, sort);
            if (update){
                return success("收藏成功");
            }else{
                return error("收藏失败");
            }
        }else {
            boolean update = isUpdate(id, sort);
            if (update){
                return success("取消收藏成功");
            }else{
                return error("取消收藏失败");
            }
        }

    }

    private boolean isUpdate(Long id, Integer sort) {
        LambdaUpdateWrapper<TqCars> updateWrapper = new LambdaUpdateWrapper<>();
        // 假设你要根据name更新email
        updateWrapper.set(TqCars::getSort, sort).eq(TqCars::getId, id);
        boolean update = tqCarsService.update(updateWrapper);
        return update;
    }
    /**
     * 查车修份量1
     *
     * @param tqCars
     * @return
     */
    @GetMapping("/list/all")
    public TableData listAll(TqCarVo tqCars) {
        // 确保layerType有默认值或明确的值
        if (StringUtils.isEmpty(tqCars.getLayerType())) {
            tqCars.setLayerType("整体"); // 或者其他默认处理逻辑
        }
        List<TqCarsDto> uniqueCars = tqCarsService.selectCarsList(tqCars);
        List<TqCarsDto> tqCarsList = tqCarsService.selectALLsList(tqCars);

//        List<TqCarsDto> uniqueCars = tqCarsList.stream()
//                // 基于id去重，保留最新元素
//                .collect(Collectors.collectingAndThen(
//                        Collectors.toMap(TqCarsDto::getId, Function.identity(), (oldValue, newValue) -> oldValue),
//                        m -> new ArrayList<>(m.values()))
//                )
//                .stream()
//                // 限制获取的数量
//                .limit(7)
//                .collect(Collectors.toList());

        // 将去重后的TqCarsDto转换为TqCarsInfo
        List<TqCarsInfo> tqCarsInfo = BeanCopyUtils.copyBeanList(uniqueCars, TqCarsInfo.class);
        // 调整逻辑，确保只处理匹配的配色方案和层
        // 转换并分组配色方案详情
        List<Map<String, Object>> queryResults = convertToMapList(tqCarsList);
        List<ColorSchemeDetail> colorSchemeDetails = packageDataWithSeq(queryResults, tqCars);

        // 组合数据并返回
        Map<String, Object> combinedResult = new HashMap<>();
        combinedResult.put("carInfos", tqCarsInfo);
        combinedResult.put("colorSchemeDetails", colorSchemeDetails);

        return new TableData(combinedResult);
    }

    /**
     * 查车修份量2
     *
     * @param tqCars
     * @return
     */
    @GetMapping("/list/all2")
    public TableData listAll2(TqCarVo tqCars) {
        // 确保layerType有默认值或明确的值
        if (StringUtils.isEmpty(tqCars.getLayerType())) {
            tqCars.setLayerType("整体"); // 或者其他默认处理逻辑
        }
        List<TqCarsDto> uniqueCars = tqCarsService.selectCarsList(tqCars);
        List<TqCarsDto> tqCarsList = tqCarsService.selectALLsList(tqCars);

//        List<TqCarsDto> uniqueCars = tqCarsList.stream()
//                // 基于id去重，保留最新元素
//                .collect(Collectors.collectingAndThen(
//                        Collectors.toMap(TqCarsDto::getId, Function.identity(), (oldValue, newValue) -> oldValue),
//                        m -> new ArrayList<>(m.values()))
//                )
//                .stream()
//                // 限制获取的数量
//                .limit(7)
//                .collect(Collectors.toList());

        // 将去重后的TqCarsDto转换为TqCarsInfo
        List<TqCarsInfo> tqCarsInfo = BeanCopyUtils.copyBeanList(uniqueCars, TqCarsInfo.class);

        // 调整逻辑，确保只处理匹配的配色方案和层
        // 转换并分组配色方案详情
        List<Map<String, Object>> queryResults = convertToMapList(tqCarsList);
        List<ColorSchemeDetail> colorSchemeDetails = packageDataWithSeq(queryResults, tqCars);

        // 组合数据并返回
        Map<String, Object> combinedResult = new HashMap<>();
        combinedResult.put("carInfos", tqCarsInfo);
        combinedResult.put("colorSchemeDetails", colorSchemeDetails);

        return new TableData(combinedResult);
    }


    public List<ColorSchemeDetail> packageDataWithSeq(List<Map<String, Object>> queryResults, TqCarVo tqCars) {
        // 使用Map按配色方案标题分组，内层使用另一个Map区分底层和面层的详情
        Map<String, Map<String, List<ColorDetail>>> dataMap = new HashMap<>();
        // 新增一个Map来收集每个title对应的remark
        List<String> titleToRemark = new ArrayList<>();
        Map<String, String> titleToRemarkMap = new HashMap<>();
        // 分别获取面层和底层的调整因子，若未提供则使用默认值100
        Double surfaceWeightMultiplier = Optional.ofNullable(tqCars.getSurfaceWeightMultiplier()).orElse(100.00);
        Double baseWeightMultiplier = Optional.ofNullable(tqCars.getBaseWeightMultiplier()).orElse(100.00);
        for (Map<String, Object> result : queryResults) {
            String title = (String) result.get("title");

            Object obj1 = result.get("schemeRemark");
            String schemeRemark = null;
            if (obj1 != null) {
                schemeRemark = (String) obj1;
            }
            String layerType = (String) result.get("layerType");
            double total = Double.parseDouble((String) result.get("total"));
            double multiplier = "底层".equals(layerType) ? baseWeightMultiplier : surfaceWeightMultiplier;
            titleToRemark.add(schemeRemark);
            titleToRemarkMap.put(title, schemeRemark);
            // 初始化或获取对应标题的内部Map
            dataMap.putIfAbsent(title, new HashMap<>());
            Map<String, List<ColorDetail>> innerMap = dataMap.get(title);

            // 获取或初始化details列表，根据层类型区分
            List<ColorDetail> detailsList = innerMap.computeIfAbsent(layerType, k -> new ArrayList<>());
            double multiplierToUse = title.equals(tqCars.getColorSchemeName()) ? multiplier : 100;
            double rawCurrentWeight = Double.parseDouble((String) result.get("netWeight"));
            double currentWeight = (rawCurrentWeight / total) * multiplierToUse; // 先计算未格式化的当前重量


            // 使用DecimalFormat来格式化，保留三位小数
            DecimalFormat df = new DecimalFormat("#.000");
            currentWeight = Double.parseDouble(df.format(currentWeight));

            double cumulativeWeight = calculateCumulativeWeight(detailsList, currentWeight); // 累积重量计算逻辑可能也需要调整以保持三位小数
            cumulativeWeight = Double.parseDouble(df.format(cumulativeWeight)); // 同样格式化累积重量

            ColorDetail detail = new ColorDetail();
            detail.setSeq(detailsList.size() + 1);
            detail.setCode((String) result.get("tintCode"));
            detail.setName((String) result.get("tintName"));
            detail.setWeight(currentWeight);
            detail.setCumulative(cumulativeWeight);
            detailsList.add(detail);
        }

        // 将数据映射转换为ColorSchemeDetail列表
        List<ColorSchemeDetail> formattedData = new ArrayList<>();
        for (Map.Entry<String, Map<String, List<ColorDetail>>> entry : dataMap.entrySet()) {
            String title = entry.getKey();
            Map<String, List<ColorDetail>> innerMap = entry.getValue();

            ColorSchemeDetail colorScheme = new ColorSchemeDetail();
            colorScheme.setTitle(title);
            colorScheme.setRemark1(titleToRemarkMap.get(title));
            colorScheme.setBottomDetails(innerMap.getOrDefault("底层", Collections.emptyList()));
            colorScheme.setSurfaceDetails(innerMap.getOrDefault("面层", Collections.emptyList()));
            formattedData.add(colorScheme);
        }
        return formattedData;
    }


    private double calculateCumulativeWeight(List<ColorDetail> detailsList, double currentWeight) {
        double cumulativeWeight = 0.0;
        if (!detailsList.isEmpty()) {
            ColorDetail lastDetail = detailsList.get(detailsList.size() - 1);
            cumulativeWeight = lastDetail.getCumulative(); // 获取最后一个条目的累积重量
        }
        // 由于currentWeight已经是调整后的值，这里直接累加即可
        return cumulativeWeight + currentWeight;
    }


    public List<Map<String, Object>> convertToMapList(List<TqCarsDto> tqCarsList) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TqCarsDto tqCars : tqCarsList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", tqCars.getId());
            map.put("brand", tqCars.getBrand());
            map.put("model", tqCars.getModel());
            map.put("colorName", tqCars.getColorName());
            map.put("year", tqCars.getYear());
            map.put("paintBrand", tqCars.getPaintBrand());
            map.put("layerType", tqCars.getLayerType());
            map.put("imageUrl", tqCars.getImageUrl());
            map.put("originalColorCode", tqCars.getOriginalColorCode());
            map.put("title", tqCars.getTitle());
            map.put("schemeRemark", tqCars.getSchemeRemark());
            map.put("total", tqCars.getTotal());
            map.put("tintCode", tqCars.getTintCode());
            map.put("tintName", tqCars.getTintName());
            map.put("netWeight", tqCars.getNetWeight());


            mapList.add(map);
        }
        return mapList;
    }

    // 判断字符串是否全为英文字母
    private boolean isEnglish(String str) {
        return str.chars().allMatch(Character::isLetter) && str.chars().allMatch(c -> (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
    }

    @GetMapping("/list/brand")
    public Map<Character, List<String>> listBrand() {
        LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(TqCars::getBrand);
        List<TqCars> list = tqCarsService.list(wrapper);

        List<String> sortedBrands = list.stream()
                .map(TqCars::getBrand)
                .distinct()
                .sorted(Comparator.comparing(this::getFirstLetter))
                .collect(Collectors.toList());

        Map<Character, List<String>> categorizedBrands = new LinkedHashMap<>();
        for (String brand : sortedBrands) {
            String firstLetter = getFirstLetter(brand);
            char firstChar = firstLetter.charAt(0);
            categorizedBrands.computeIfAbsent(firstChar, k -> new ArrayList<>()).add(brand);
        }

        // 将数据转换为以'A', 'B', 'C', ...为键的Map
        Map<Character, List<String>> abcCategorizedBrands = new LinkedHashMap<>();
        for (char i = 'A'; i <= 'Z'; i++) {
            abcCategorizedBrands.put(i, categorizedBrands.getOrDefault(i, Collections.emptyList()));
        }
        // 打印Map的内容
        abcCategorizedBrands.forEach((key, value) -> {
            System.out.println("Key: " + key + ", Brands: " + value);
        });
        return abcCategorizedBrands;
    }

    // 获取首字母，英文直接取，中文调用PinyinUtil
    private String getFirstLetter(String brand) {
        if (isEnglish(brand)) {
            return brand.substring(0, 1);
        } else {
            return PinyinUtil.getFirstLetter(brand);
        }
    }


    /**
     * 车型下拉框
     *
     * @return
     */
    @GetMapping("/list/car")
    public TableDataInfo listCar(String brand) {
        LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(TqCars::getModel);
        wrapper.eq(TqCars::getBrand, brand);
        List<TqCars> list = tqCarsService.list(wrapper);
        List<String> model = list.stream()
                .map(TqCars::getModel)
                .distinct() // 添加distinct操作进行去重
                .collect(Collectors.toList());
        return getDataTable(model);
    }

    /**
     * 汽车颜色下拉框
     *
     * @return
     */
    @GetMapping("/list/color")
    public TableDataInfo listColor(String brand, String model) {
        LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(TqCars::getColorName).eq(TqCars::getBrand, brand).eq(TqCars::getModel, model);
        List<TqCars> list = tqCarsService.list(wrapper);
        List<String> color = list.stream()
                .map(TqCars::getColorName)
                .distinct() // 添加distinct操作进行去重
                .collect(Collectors.toList());
        return getDataTable(color);
    }


    /**
     * 油漆品牌下拉框
     *
     * @return
     */
    @GetMapping("/list/paint")
    public TableDataInfo listPaint() {
        LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(TqCars::getPaintBrand);
        List<TqCars> list = tqCarsService.list(wrapper);
        List<String> paintBrands = list.stream()
                .map(TqCars::getPaintBrand)
                .distinct() // 添加distinct操作进行去重
                .collect(Collectors.toList());
        return getDataTable(paintBrands);
    }

    /**
     * 综合查询
     *
     * @return
     */
    @GetMapping("/list/paint/all")
    public List<TqCarsInfo> searchCar(String param) {
        List<TqCarsInfo> list = tqCarsService.listByparam(param);
        for (TqCarsInfo carsInfo : list) {
            carsInfo.setId(String.valueOf(carsInfo.getId()));
        }
        return list;
    }

    /**
     * 导出汽车信息列表
     */
    @PreAuthorize("@ss.hasPermi('paint:cars:export')")
    @Log(title = "汽车信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TqCarsInfo tqCars) {
        List<TqCarsInfo> list = tqCarsService.selectTqCarsList(tqCars);
        ExcelUtil<TqCarsInfo> util = new ExcelUtil<TqCarsInfo>(TqCarsInfo.class);
        util.exportExcel(response, list, "汽车信息数据");
    }

    /**
     * 获取汽车信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('paint:cars:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tqCarsService.selectTqCarsById(id));
    }



    /**
     * 新增汽车以及色母信息
     */

    @PostMapping("/insertCarAndColorScheme")
    public AjaxResult insertCarAndColorScheme(@RequestBody CarColorSchemeDTO carColorSchemeDTO) {
        String result = null;
        try {
            result = tqCarsService.insertTqCarsAll(carColorSchemeDTO);
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("插入失败：" + result + e.getMessage());
        }
    }


    /**
     * 修改色母信息接口
     */
    @PreAuthorize("@ss.hasPermi('paint:cars:edit')")
    @Log(title = "汽车信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editCar(@RequestBody CarColorSchemeDTO carColorSchemeDTO) {
        List<Long> ids = new ArrayList<>();
        ids.add(Long.valueOf(carColorSchemeDTO.getCarInfo().getId()));
        removeCar(ids);
        String result = null;
        try {
            result = tqCarsService.insertTqCarsAll(carColorSchemeDTO);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            return AjaxResult.error("插入失败：" + result + e.getMessage());
        }

    }

    /**
     * 删除图片
     */
//    @PreAuthorize("@ss.hasPermi('paint:cars:edit')")
    @Log(title = "汽车信息", businessType = BusinessType.UPDATE)
    @PutMapping("/picture")
    public AjaxResult removePicture(@RequestBody TqCars tqCars) {
        // 创建UpdateWrapper实例，用于构建更新条件
        LambdaUpdateWrapper<TqCars> updateWrapper = new LambdaUpdateWrapper<>();

        // 设置更新条件为userId，并指定description字段更新为null
        updateWrapper.eq(TqCars::getId, tqCars.getId()).set(TqCars::getImageUrl, null);
        // 调用update方法执行更新操作
        return toAjax(tqCarsService.update(updateWrapper));
    }


    /**
     * 删除车辆信息
     *
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('paint:cars:remove')")
    @Log(title = "汽车信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/new/{ids}")
    public AjaxResult removeCar(@PathVariable List<Long> ids) {
        // 删除汽车信息
        tqCarsService.removeBatchByIds(ids);
        // 查询配色信息
        LambdaQueryWrapper<TqColorschemes> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TqColorschemes::getCarId, ids);
        List<TqColorschemes> list = tqColorschemesService.list(wrapper);
        List<Long> colorschemeIds = list.stream().map(TqColorschemes::getId).collect(Collectors.toList());
        //删除配色信息
        tqColorschemesService.removeBatchByIds(colorschemeIds);
        //删除关联信息
        LambdaQueryWrapper<TqSchemetints> wrappers = new LambdaQueryWrapper<>();
        wrappers.in(TqSchemetints::getSchemeId, colorschemeIds);
        tqSchemetintsService.remove(wrappers);

        return AjaxResult.success("删除成功");
    }


}
